package com.matrix.tool.ui.tool

import android.Manifest.permission.MANAGE_EXTERNAL_STORAGE
import android.Manifest.permission.READ_EXTERNAL_STORAGE
import android.Manifest.permission.READ_MEDIA_IMAGES
import android.Manifest.permission.READ_MEDIA_VIDEO
import android.Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED
import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
import android.content.DialogInterface
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.UriUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.matrix.basecore.base.BaseActivity
import com.matrix.basecore.constant.Constant
import com.matrix.basecore.utils.glide.GlideUtil
import com.matrix.editor.EditorActivity
import com.matrix.editor.bean.EditorResult
import com.matrix.editor.bean.EditorSetup
import com.matrix.tool.R
import com.matrix.tool.databinding.ActivityPictureEditBinding
import java.io.File

@Route(path = Constant.ARouterPath.PictureEditActivityPath)
class PictureEditActivity : BaseActivity<ActivityPictureEditBinding>() {

    private var uri: Uri? = null
    private var editPath: String? = null
    private val permissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            checkPermission()
        }

    private val photoLauncher =
        registerForActivityResult(
            ActivityResultContracts.GetContent()
        ) { uri ->
            uri.let {
                if (uri != null) {
                    loadImages(uri)
                    mViewBinding.llEdit.performClick()
                }
            }
        }
    private val activityLauncher =
        registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            if (result.resultCode == RESULT_OK) {
                val editorResult: EditorResult? =
                    result.data!!.getSerializableExtra(RESULT_OK.toString() + "") as EditorResult?
                editPath = editorResult!!.editor2SavedPath
                Glide.with(this).load(editPath)
                    .diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true)
                    .into(mViewBinding.phView)
            }
        }

    override fun getViewBinding(): ActivityPictureEditBinding {
        enableEdgeToEdge()
//        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
//            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
//            insets
//        }
        return ActivityPictureEditBinding.inflate(layoutInflater)
    }

    override fun initView() {
        //立即申请权限
//        requestPermissions()
        mViewBinding.includeTitle.tvTitle.text = "图片编辑"
    }

    override fun initListener() {
        mViewBinding.includeTitle.ivBack.setOnClickListener {
            finish()
        }

        mViewBinding.rlPermission.setOnClickListener {
            requestPermissions()
        }

        mViewBinding.ivDelete.setOnClickListener {
            mViewBinding.rlPermission.visibility = View.GONE
        }
        mViewBinding.llEmpty.setOnClickListener {
            requestPermissions()
        }
        mViewBinding.tvReChoose.setOnClickListener {
            editPath = null
            requestPermissions()
        }

        mViewBinding.llEdit.setOnClickListener {
            if (uri != null) {
                if (editPath != null) {
                    startEditActivity(editPath!!)
                } else {
                    startEditActivity(UriUtils.uri2File(uri).path)
                }
            } else {
                requestPermissions()
            }
        }

        mViewBinding.llSave.setOnClickListener {
            if (editPath != null) {
                var ab = AlertDialog.Builder(this).create();
                ab.setTitle("保存")
                ab.setMessage("确定图片保存到：" + destPath())
                ab.setButton(
                    DialogInterface.BUTTON_POSITIVE, "确定"
                ) { _, _ ->
                    FileUtils.copy(
                        editPath,
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path + File.separator + destPath()
                    )
                    ab.dismiss()
                    ToastUtils.showShort("保存成果")
                }
                ab.show()
            } else {
                ToastUtils.showShort("暂未编辑图片")
            }
        }

        mViewBinding.llShare.setOnClickListener {

        }
    }

    private fun PictureEditActivity.destPath(): String {
        var time = System.currentTimeMillis().toString()
        return Constant.ImagePath + time.substring(time.length - 4) + File(editPath).name
    }


    private fun loadImages(uri: Uri) {
        this.uri = uri
        mViewBinding.llEmpty.visibility = View.GONE
        GlideUtil.loadImage(
            uri.toString(),
            this,
            mViewBinding.phView,
            DiskCacheStrategy.NONE,
            R.mipmap.icon_empty
        )
        GlideUtil.loadBlurImage(
            uri.toString(),
            this,
            mViewBinding.ivBlur,
            1,
            4,
            R.mipmap.icon_empty
        )
    }

    private fun requestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            permissionLauncher.launch(
                arrayOf(
                    READ_MEDIA_IMAGES,
                    READ_MEDIA_VIDEO,
                    WRITE_EXTERNAL_STORAGE,
                    READ_EXTERNAL_STORAGE
                )
            )
        } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.TIRAMISU) {
            permissionLauncher.launch(
                arrayOf(
                    READ_MEDIA_IMAGES,
                    READ_MEDIA_VIDEO,
                    WRITE_EXTERNAL_STORAGE,
                    READ_EXTERNAL_STORAGE)
            )
        } else {
            permissionLauncher.launch(arrayOf(READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE))
        }
    }

    private fun checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
            && (ContextCompat.checkSelfPermission(this, READ_MEDIA_IMAGES) == PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(
                this,
                READ_MEDIA_VIDEO
            ) == PERMISSION_GRANTED)
        ) {
            // Full access on Android 13 (API level 33) or higher
            mViewBinding.rlPermission.visibility = View.GONE
            photoLauncher.launch("image/*")
        } else if (
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE &&
            ContextCompat.checkSelfPermission(
                this,
                READ_MEDIA_VISUAL_USER_SELECTED
            ) == PERMISSION_GRANTED
        ) {
            // Partial access on Android 14 (API level 34) or higher
            mViewBinding.text.text = "你已授权访问部分相册，点击添加更多"
            mViewBinding.rlPermission.visibility = View.VISIBLE
        } else if (ContextCompat.checkSelfPermission(
                this,
                READ_EXTERNAL_STORAGE
            ) == PERMISSION_GRANTED
        ) {
            // Full access up to Android 12 (API level 32)
            mViewBinding.rlPermission.visibility = View.GONE
            photoLauncher.launch("image/*")
        } else {
            // Access denied
            mViewBinding.text.text = "你还未授权访问相册的照片的权限，点击申请"
            mViewBinding.rlPermission.visibility = View.VISIBLE
        }
    }

    private fun startEditActivity(path: String) {
        val sdCardDir =
            File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), Constant.CachePath)
        var savePath = sdCardDir.path
        FileUtils.createOrExistsDir(savePath)
        var edit = EditorSetup(path, path, savePath + "/" + File(path).name, true)
        activityLauncher.launch(EditorActivity.intent(this, edit))
    }
}